package cn.samehope.pet.web.animalRecord;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.samehope.pet.Consts;
import cn.samehope.pet.interceptor.WxInterceptor;
import cn.samehope.pet.interceptor.WxJsSdkInterceptor;
import cn.samehope.pet.model.PetAnimal;
import cn.samehope.pet.model.PetAnimalRecord;
import cn.samehope.pet.model.PetLog;
import cn.samehope.pet.model.PetMember;
import cn.samehope.pet.util.DateFormatUtil;
import cn.samehope.pet.util.FileUtil;
import cn.samehope.pet.util.RelativeDateFormart;
import cn.samehope.pet.web.animal.PetAnimalService;

/**
 * 宠物成长记录CONTROLLER
 * @author LD
 *
 */
public class PetAnimalRecordController extends Controller{
	
	static PetAnimalRecordService srv = PetAnimalRecordService.me;
	
	static PetAnimalService psrv = PetAnimalService.me;
	
	public void getList(){
		String openId = getPara("open_id");
		List<Record> list = Db.find(" select * from pet_animal_record where animal_by = ? ", openId);
		renderJson(list);
	}
	
	@Before({WxInterceptor.class, WxJsSdkInterceptor.class})
	public void index(){
		setAttr("animal_id", getPara("animal_id"));
		String open_id_session = getSessionAttr("open_id_session");
		Record record = Db.findFirst("select * from ims_ewei_shop_member where openid = ? ", open_id_session);
		setAttr("record", record);
		Record picRecord = Db.findFirst("select * from pet_member where open_id = ? ", open_id_session);
		setAttr("picRecord", picRecord);
		//保存访问日志
		PetLog pl = new PetLog();
		pl.setTitle("pyq");
		pl.setUpdateBy(open_id_session);
		pl.setUpdateDate(new Date());
		pl.save();
		render("animalRecord_list_all.html");
	}
	
	/**
	 * 成长记录
	 */
	@Before({WxInterceptor.class, WxJsSdkInterceptor.class})
	public void person(){
		setAttr("animal_id", getPara("animal_id"));
		String open_id_session = getSessionAttr("open_id_session");
		Record record = Db.findFirst("select * from ims_ewei_shop_member where openid = ? ", open_id_session);
		setAttr("record", record);
		Record picRecord = Db.findFirst("select * from pet_member where open_id = ? ", open_id_session);
		setAttr("picRecord", picRecord);
		render("animalRecord_list_person.html");
	}
	
	@Before({WxInterceptor.class})
	public void review(){
		render("animalRecord_list_review.html");
	}
	
	/**
	 * 成长记录列表
	 */
	public void list(){
		int pageNumber = getParaToInt("pageNumber");
		String type = getPara("type");
		Page<Record> page = null;
		if(type.equals("all")){
			page = Db.paginate(pageNumber
					, Consts.pageSize
					, "select a.*, b.avatar, b.nickname "
					, " from pet_animal_record a LEFT JOIN ims_ewei_shop_member b ON a.animal_by = b.openid order by record_date desc"
					);
		}else{
			String open_id_session = getSessionAttr("open_id_session");
			page = Db.paginate(pageNumber
					, Consts.pageSize
					, "select a.*, b.avatar, b.nickname "
					, " from pet_animal_record a LEFT JOIN ims_ewei_shop_member b ON a.animal_by = b.openid where a.animal_by = ? order by record_date desc"
					, open_id_session);
		}
		List<Record> list = page.getList();
		List<Record> rList = new ArrayList<Record>();
		for(Record e:list){
			e.set("record_date_formart", RelativeDateFormart.format((Date)e.get("record_date")));
			e.set("record_date_cn", DateFormatUtil.getDateStr(e.getStr("record_date")));
			e.set("record_date_year", DateFormatUtil.getDateYear(e.getStr("record_date")));
			e.set("record_date_month", DateFormatUtil.getDateMonth(e.getStr("record_date")));
			rList.add(e);
			LogKit.info(JsonKit.toJson(e));
		}
		Page<Record> npage = new Page<Record>(rList, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
		renderJson(npage);
	}
	
	/**
	 * 跳转到宠物成长记录编辑页
	 */
	@Before({WxInterceptor.class, WxJsSdkInterceptor.class})
	public void forward(){
		String id = getPara("id");
		
		//获取宠物成长记录
		PetAnimalRecord par = srv.findById(id);
		setAttr("petAnimalRecord", par);
		
		//获取宠物名称
		String animalName = "";
		if(null != par && null != par.getAnimalId()){
			PetAnimal pa = psrv.findById(par.getAnimalId());
			animalName = pa.getName();
			
			String[] picList = par.getPics().split(",");
			setAttr("picList", picList);
		}
		setAttr("animalName", animalName);
		
		//获取用户手机号
		String open_id_session = getSessionAttr("open_id_session");
		Record record = Db.findFirst("select * from ims_ewei_shop_member where openid = ? ", open_id_session);
		setAttr("mobile", record.get("mobile"));
		LogKit.info(JsonKit.toJson(record));
		
		render("animalRecord_detail.html");
	}
	
	public void test(){
		render("test.html");
	}
	
	public void save(){
		PetAnimalRecord par = getModel(PetAnimalRecord.class);
		String open_id_session = getSessionAttr("open_id_session");
		
		String animalName = getPara("animalName", "");
		Record record = Db.findFirst("select * from pet_animal where name = ? ", animalName);
		
		par.setAnimalId(record.getInt("id"));
		par.setRecordBy(open_id_session);
		par.setAnimalBy(record.getStr("open_id"));
		boolean flag = false;
		if(null != par){
			Date d = new Date();
			if(null != par.getId()){
				par.setRecordDate(d);
				flag = srv.update(par);
			}else{
				par.setRecordDate(d);
				flag = srv.save(par);
			}
		}
		Ret ret;
		if(flag){
			ret = Ret.ok();
		}else{
			ret = Ret.fail();
		}
		renderJson(ret);
	}
	
	public void saveImages() {
        String mediaId = getPara("mediaId", "");
        String open_id_session = getSessionAttr("open_id_session");
		Record record = Db.findFirst("select * from ims_ewei_shop_member where openid = ? ", open_id_session);
        String fileName = System.currentTimeMillis()+"";
        String filePath = FileUtil.saveImageToDisk(Consts.petPath + File.separator + record.getStr("id") , fileName, mediaId);
        String flag = getPara("flag", "");
        if(flag.equals("insert")){
        	PetMember pm = new PetMember();
        	pm.setOpenId(open_id_session);
        	pm.setPic(filePath);
        	pm.setUpdateDate(new Date());
        	Record picRecord = Db.findFirst("select * from pet_member where open_id = ? ", open_id_session);
        	if(null != picRecord && picRecord.get("id") != null){
        		pm.setId(picRecord.getInt("id"));
        		pm.update();
        	}else{
        		pm.save();
        	}
        	LogKit.info("----------pm------"+JsonKit.toJson(pm));
        }
        LogKit.info("----------fileName------"+filePath);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("filePath", filePath);
        map.put("fileName", fileName);
        renderJson(map);
	}
	
	public void animalList(){
		String openId = getPara("open_id");
		String mobile = getPara("mobile");
		List<Record> recordList = null;
		if(StringUtils.isBlank(mobile)){
			recordList = Db.find("select * from pet_animal where open_id = ? ", openId);
		}else{
			recordList = Db.find("select * from pet_animal where open_id in(select openid from ims_ewei_shop_member where mobile = ? ) ", mobile);
		}
		LogKit.info(JsonKit.toJson(recordList));
		renderJson(recordList);
	}

}
